package com.zmn.plat.admin.controller.servcategory;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zmn.common.dto2.ResponseDTO;
import com.zmn.plat.common.exception.PlatException;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.plat.common.constant.ProductConsts;
import com.zmn.plat.manager.dictionary.ProductDict;
import com.zmn.plat.model.entity.category.BaseCategory;
import com.zmn.plat.model.entity.product.ServProduct;
import com.zmn.plat.model.entity.product.ServProductQuery;
import com.zmn.plat.model.entity.servcategory.ServCategory;
import com.zmn.plat.model.vo.servcategory.ServCategoryVO;

/**
 * @author duanzuocai
 * @version v1.0
 * @since 2018/10/20 9:15
 */
@Controller
@RequestMapping("/serv/categ/")
public class ServCategoryModifyController extends ServCategoryBaseController {

    private Logger logger = LoggerFactory.getLogger(ServCategoryModifyController.class);

    @RequiresPermissions("/serv/categ/updateStatus.action")
    @RequestMapping(value = "updateStatus")
    @ResponseBody
    public ResponseDTO updateStatus(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "ids", defaultValue = "") String ids, @RequestParam(value = "status", defaultValue = "0") int status) {

        if (StringUtil.isBlank(ids)) {
            return ResponseDTO.fail("请选择要更改状态的分类！");
        }

        List<Integer> arrayIds = StringUtil.convertStrsToList(ids);

        if (Objects.equals(GlobalConsts.NO, status)) {
            ServProductQuery query = new ServProductQuery();
            query.setServCategIds(arrayIds);
            query.setStatus(GlobalConsts.YES);
            query.setShowType(ProductDict.ERP_PRODUCT_TYPE);
            List<ServProduct> servProducts = servProductService.listByQuery(query);
            List<Integer> servCategIds = servProducts.stream().map(ServProduct::getServCategId).distinct().collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(servCategIds)) {
                return ResponseDTO.fail("服务分类下的产品需全部下架");
            }
        }

        servCategoryService.updateStatusBatch(arrayIds, status, getMcStaffRealName());

        return ResponseDTO.success(true, "操作成功！");
    }

    @RequestMapping(value = "updateSort")
    @ResponseBody
    @SuppressWarnings("Duplicates")
    public ResponseDTO updateSort(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "id", defaultValue = "0") Integer categId, @RequestParam(value = "sort", defaultValue = "0") Integer sort) {

        if (categId == 0) {
            return ResponseDTO.fail("请选择要更改排序的分类！");
        }
        if (sort == 0) {
            return ResponseDTO.fail("请设置分类排序值！");
        }

        servCategoryService.updateSortKey(categId, sort, getMcStaffRealName());
        return ResponseDTO.success(true,"操作成功！");
    }

    @RequiresPermissions("/serv/categ/updateName.action")
    @RequestMapping(value = "updateName")
    @ResponseBody
    public ResponseDTO updateName(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "id", defaultValue = "0") Integer categId, @RequestParam(value = "name", defaultValue = "0") String name) {
        if (categId == 0) {
            return ResponseDTO.fail("请选择要更改排序的分类！");
        }
        if (StringUtils.isEmpty(name)) {
            return ResponseDTO.fail("请设置名称值！");
        }

        servCategoryService.updateNameKey(categId, name, getMcStaffRealName());

        return ResponseDTO.success(true,"操作成功！");
    }

    @RequiresPermissions("/serv/categ/addEdit.action")
    @RequestMapping(value = "addEdit")
    @ResponseBody
    public ResponseDTO addEdit(HttpServletRequest request, HttpServletResponse response, @RequestBody ServCategory category) {
        try {
            servCategoryBService.addEdit(category, getMcStaffRealName());
            return ResponseDTO.success(true,"操作成功");
        }catch (PlatException e){
            return ResponseDTO.fail(e.getErrorCode(),e.getMessage());
        }catch (Exception e){
            logger.error("addEdit error",e);
            return ResponseDTO.fail("操作失败");
        }

    }

    @RequestMapping(value = "classifyProduct")
    @SuppressWarnings("Duplicates")
    public ModelAndView list(@RequestParam(value = "servCategId", defaultValue = "0") Integer servCategId) {
        List<BaseCategory> categOnes = baseCategoryService.listByParentId(GlobalConsts.TOP_ID, GlobalConsts.YES);
        List<ServCategoryVO> servAssCategoryItems = servAssCategoryService.listClassificationLevelTwo();
        List<ServCategoryVO> servAssCategoryByServId =
            servAssCategoryService.findServAssCategoryByServIdAndShowType(servCategId, ProductConsts.ERP_PRODUCT_TYPE);
        ServCategory servCategory = servCategoryService.findByKey(servCategId);
        if (servCategory == null) {
            servCategory = new ServCategory();
        }
        Map<Integer, List<ServCategoryVO>> map =
            servAssCategoryItems.stream().collect(Collectors.groupingBy(ServCategoryVO::getCategOneId));

        for (Map.Entry<Integer, List<ServCategoryVO>> entry : map.entrySet()) {
            for (ServCategoryVO servCategoryVo : entry.getValue()) {
                for (ServCategoryVO innerServCategoryVO : servAssCategoryByServId) {
                    if (innerServCategoryVO.getCategOneId().equals(servCategoryVo.getCategOneId())
                        && innerServCategoryVO.getCategId().equals(servCategoryVo.getCategId())) {
                        servCategoryVo.setRelated(true);
                        break;
                    } else {
                        servCategoryVo.setRelated(false);
                    }
                }

            }
        }

        ModelAndView mav = new ModelAndView("servcategroy/classifyproduct");

        mav.addObject("servCategId", servCategId);
        mav.addObject("servCategory", servCategory);
        mav.addObject("items", servAssCategoryItems);
        mav.addObject("categOnes", categOnes);
        mav.addObject("map", map);
        return mav;
    }

    @RequestMapping(value = "updateSimpleSpell")
    @ResponseBody
    @RequiresPermissions("/serv/categ/updateSimpleSpell.action")
    public ResponseDTO updateShowSimpleSpell(HttpServletRequest request, HttpServletResponse response,
                                             @RequestParam(value = "id", defaultValue = "0") Integer categId,
                                             @RequestParam(value = "simpleSpell", defaultValue = "") String simpleSpell) {

        if (categId == 0) {
            return ResponseDTO.fail("请选择要更改的分类！");
        }
        if (StringUtil.isBlank(simpleSpell)) {
            return ResponseDTO.fail("请设置简称！");
        }

        servCategoryService.updateSimpleSpellByKey(categId, simpleSpell.toUpperCase(), getMcStaffRealName());
        return ResponseDTO.success(true,"操作成功！");
    }

    private void check(ServCategory category) {
        if (!NumberUtil.isPositiveInteger(category.getSort())) {
            category.setSort(GlobalConsts.TOP_ID);
        }
    }
}
